package com.yanqu.road.dataHelper.action.excel;

import com.alibaba.druid.util.JdbcUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yanqu.road.dataHelper.manager.BaseMgr;
import com.yanqu.road.dataHelper.manager.DataMgr;
import com.yanqu.road.entity.activity.UnionActivityConditionData;
import com.yanqu.road.entity.servercenter.CrossServerInfo;
import com.yanqu.road.entity.servercenter.DbInfo;
import com.yanqu.road.entity.union.UnionBaseInfo;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.Logger;

import java.math.BigInteger;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CrossOreWar {

    public CrossOreWar(CrossServerInfo crossServerInfo) {
        this.crossServerInfo = crossServerInfo;
        initDb();
    }

    Connection connection;

    CrossServerInfo crossServerInfo;

    private void initDb(){
        DbInfo dbInfo = crossServerInfo.getDbInfos().get(0);
        try {
            connection =  DriverManager.getConnection("jdbc:mysql://" + dbInfo.getIp() + ":" + dbInfo.getPort() + "/" + dbInfo.getDbName()+"?useUnicode=true&character_set_server=utf8mb4&useSSL=false", dbInfo.getUserName(), dbInfo.getPassword());
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("连接失败！");
        }
    }


    public void go(String activityIdIn ){
        Map<Integer,Map<String, UnionActivityConditionData>> listMap = getUnionCondition(activityIdIn);
        DataMgr.addUnionData(listMap);
    }

    private Map<Integer,Map<String, UnionActivityConditionData>> getUnionCondition(String activityIdIn) {
        Map<Integer,Map<String, UnionActivityConditionData>> dataMap = new ConcurrentHashMap<>();
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "SELECT * FROM t_c_union_activity_condition WHERE activityId in (" + activityIdIn + ")";
        try {
            call = connection.prepareCall(sql);
            int i=1;
            rs = call.executeQuery();
            while (rs.next()) {
                UnionActivityConditionData data = parseData(rs);
                if(!dataMap.containsKey(data.getActivityId())){
                    dataMap.put(data.getActivityId(),new ConcurrentHashMap<>());
                }
                dataMap.get(data.getActivityId()).put(data.getUnionUid(),data);
            }
        } catch (SQLException ex) {
           getLogger().error("异常错误", ex);
        } finally {
            closeConnection(call, rs);
        }
        return dataMap;
    }

    protected UnionActivityConditionData parseData(ResultSet rs) throws SQLException {
        UnionActivityConditionData data = new UnionActivityConditionData();
        data.setUnionUid(rs.getString("unionUid"));
        data.setActivityId(rs.getInt("activityId"));
        data.setConditionId(rs.getInt("conditionId"));
        String value = rs.getString("value");
        if(!StringUtils.isNullOrEmpty(value)) {
            data.setValue(new BigInteger(value));
        }
        value = rs.getString("preValue");
        if(!StringUtils.isNullOrEmpty(value)){
            data.setPreValue(new BigInteger(value));
        }
        data.setGetReward(rs.getBoolean("isGetReward"));
        data.setLastUpdateTime(rs.getLong("lastUpdateTime"));
        data.setConditionType(rs.getInt("conditionType"));
        data.setMemberUserIdList(StringUtils.stringToLongList(rs.getString("memberList"), ","));
        data.setInfo(rs.getString("info"));
        value = rs.getString("unionBaseInfo");
        if(null == value) {
            value = "";
        }
        UnionBaseInfo unionBaseInfo = JSON.parseObject(value, new TypeReference<UnionBaseInfo>() {});
        if(null != unionBaseInfo){
            data.setUnionBaseInfo(unionBaseInfo);
        }

        String position =  rs.getString("positionInfo");
        if(StringUtils.isNullOrEmpty(position)) {
            position = "{}";
        }
        HashMap<Long, Integer> positionMap = JSON.parseObject(position, new TypeReference<HashMap<Long, Integer>>() {
        });
        if(null != positionMap) {
            data.setMemberPositionMap(positionMap);
        }
        return data;
    }


    public void closeConnection(PreparedStatement pstmt, ResultSet rs) {
        JdbcUtils.close(rs);
//        closeConnection(pstmt);
    }

    public static Logger getLogger() {
        return BaseMgr.getLogger();
    }
}
